<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>资源申请对话框</title>
    <!-- 引入Bootstrap依赖 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <style>
        .modal-header {
            background-color: #f8f9fa;
            border-bottom: 1px solid #dee2e6;
        }
        .modal-title {
            color: #212529;
            font-weight: 600;
        }
        .modal-footer {
            border-top: 1px solid #dee2e6;
        }
        .form-label {
            font-weight: 500;
        }
        .option-item {
            padding: 10px 15px;
            border-bottom: 1px solid #eee;
            transition: background-color 0.2s;
        }
        .option-item:hover {
            background-color: #f8f9fa;
        }
        .option-item:last-child {
            border-bottom: none;
        }
        .modal-content {
            border-radius: 10px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
<div class="modal fade" id="chooseSpaceModal" tabindex="-1" aria-labelledby="chooseSpaceModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header text-white">
                <h5 class="modal-title" id="chooseSpaceModalLabel">资源导入可信空间</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <div class="modal-body">
                <p class="mb-3">请选择可信空间：</p>
                <div id="optionContainer" class="mb-4">
                    <!-- 单选选项将动态加载 -->
                    <div class="text-center py-4">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                        <p class="mt-2">加载选项...</p>
                    </div>
                </div>

                <div class="d-flex justify-content-end gap-2">
                    <button type="button" class="btn btn-secondary" id="cancelBtn" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="confirmBtn">确定</button>
                </div>
            </div>
        </div>
    </div>
</div>

<script th:inline="javascript">
    /*<![CDATA[*/
    $(function() {
        // 全局变量存储当前资源ID
        let currentResourceId = /*[[${resId}]]*/ 'default-id-123'
        openApplyDialog(currentResourceId);

        // 打开对话框并加载选项
        function openApplyDialog(resourceId) {
            // 从后端获取选项数据
            $.ajax({
                url: '/ts/list',
                type: 'GET',
                success: function(response) {
                    if(response && response.code == 200){
                        renderOptions(response.rows);
                    }
                },
                error: function() {
                    $('#optionContainer').html(`
                        <div class="alert alert-danger">
                            选项加载失败，请<a href="#" onclick="retryLoadOptions()">重试</a>
                        </div>
                    `);
                }
            });
        }

        // 渲染选项到对话框
        function renderOptions(options) {
            if (!options || options.length === 0) {
                $('#optionContainer').html('<div class="alert alert-warning">无可选选项</div>');
                return;
            }

            let optionsHtml = '';
            options.forEach((option, index) => {
                optionsHtml += `
                    <div class="option-item">
                        <div class="form-check">
                            <input class="form-check-input" type="radio"
                                   name="tspaceOption"
                                   id="option${index}"
                                   value="${option.name}"
                                   ${index === 0 ? 'checked' : ''}>
                            <label class="form-check-label w-100" for="option${index}">
                                <strong>${option.name}</strong>
                                <p class="mb-0 text-muted small">${option.purpose || ''}</p>
                            </label>
                        </div>
                    </div>
                `;
            });

            $('#optionContainer').html(optionsHtml);
        }

        // 重试加载选项
        function retryLoadOptions() {
            openApplyDialog(currentResourceId);
        }

        // 提交申请
        function submitApplication() {
            const selectedOption = $('input[name="tspaceOption"]:checked').val();
            if (!selectedOption) {
                alert('请选择一个选项');
                return;
            }

            // 禁用按钮防止重复提交
            $('#confirmBtn').prop('disabled', true).html(`
                <span class="spinner-border spinner-border-sm" role="status"></span>
                提交中...
            `);

            // 提交到后端
            $.ajax({
                url: '/ts/addRes',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    bucketName: selectedOption,
                    resId: currentResourceId
                }),
                success: function(response) {
                    if (response && response.code == 200) {
                        // 关闭当前模态框
                        if (window.parent.closeModal) {
                          window.parent.closeModal();
                        }
                    } else {
                        showErrorAlert(response.message || '提交失败');
                    }
                },
                error: function() {
                    showErrorAlert('网络错误，请重试');
                },
                complete: function() {
                    $('#confirmBtn').prop('disabled', false).text('确定');
                }
            });
        }

        // 显示错误提示
        function showErrorAlert(message) {
            const alertHtml = `
                <div class="alert alert-danger alert-dismissible fade show position-fixed top-0 end-0 m-3" role="alert">
                    <strong>✗</strong> ${message}
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            `;
            $('body').append(alertHtml);

            // 5秒后自动消失
            setTimeout(() => {
                $('.alert-danger').alert('close');
            }, 5000);
        }

        // 确定按钮点击事件
        $('#confirmBtn').click(submitApplication);

        // 支持回车提交
        $('#chooseSpaceModal').on('keypress', function(e) {
            if (e.which === 13) {
                submitApplication();
            }
        });
    });
    /*]]>*/
</script>
</body>
</html>